package com.example.teamtribe.main.club.moment;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.example.teamtribe.common.Back;
import com.example.teamtribe.database.Posting;
import com.example.teamtribe.main.club.PostingModel;

import java.util.ArrayList;
import java.util.List;

public class MomentPresenter implements MomentContract.Presenter {

    private MomentContract.View view;
    private PostingModel model;
    private int num;

    public MomentPresenter(MomentContract.View view) {
        this.view = view;
        model = PostingModel.getInstance();
    }

    @Override
    public void start(int mode, int id) {
        List<Posting> postings = model.getLocalPostings(mode, id);
        view.clearPosts();
        num = 0;
        view.addPosts(postings);
        getPosts(mode, id, 0);
        //if (postings == null || postings.isEmpty()) {
            //view.refresh();
        //} else {
            //view.refresh();
            //view.addPosts(postings);
        //}
    }

    @Override
    public void getPosts(int mode, int id, final int offset) {
        model.getPostings(mode, id, offset, 10, new Back() {
            @Override
            public void success(@Nullable Bundle bundle) {
                List<Posting> postings = bundle.getParcelableArrayList("postings");
                if (postings == null) {
                    postings = new ArrayList<>(0);
                }
                //if (offset == 0) {
                    //view.clearPosts();
                //}
                num += postings.size();
                view.addPosts(postings);
                view.complete();
            }

            @Override
            public void failure(String meg) {
                view.showToast(meg);
            }
        });
    }

    @Override
    public void getPosts(int mode, int id) {
        getPosts(mode, id, num);
    }
}
